﻿using Dapper;
using ML.Entity;
using ML.Utils;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace ML.Repository
{
    /// <summary>
    /// 定义抽象类
    /// </summary>
    public abstract class DBFactory
    {
        /// <summary>
        /// 数据库连接
        /// </summary>
        public IDbConnection _db = new MySqlConnection(ConfigHelper.ConnectionString);

        /// <summary>
        /// 打开数据库连接
        /// </summary>
        /// <returns></returns>
        public MySqlConnection OpenConnection()
        {
            MySqlConnection connection = new MySqlConnection(ConfigHelper.ConnectionString);
            connection.Open();
            return connection;
        }

        /// <summary>
        /// 公共的分页方法
        /// </summary>
        /// <typeparam name="T">返回的实体</typeparam>
        /// <param name="criteria">查询信息</param>
        /// <param name="param"></param>
        /// <returns></returns>
        public Pager<T> GetPageData<T>(PageCriteria criteria, object param = null)
        {
            var parameters = new DynamicParameters();
            const string proc_name = "ML_ProcGetPageData";
            parameters.Add("TableName", criteria.TableName);
            parameters.Add("Field", criteria.Field);
            parameters.Add("Conditions", criteria.Conditions);
            parameters.Add("SortName", criteria.SortName);
            parameters.Add("Sort", criteria.Sort);
            parameters.Add("PageIndex", criteria.PageIndex);
            parameters.Add("PageSize", criteria.PageSize);
            parameters.Add("Total", dbType: DbType.Int32, direction: ParameterDirection.Output);
            parameters.Add("PageCount", dbType: DbType.Int32, direction: ParameterDirection.Output);

            //组装查询
            var pager = new Pager<T>();
            using (var db = OpenConnection())
            {
                pager.rows = db.Query<T>(proc_name, parameters, commandType: CommandType.StoredProcedure).ToList();
                pager.total = parameters.Get<int>("Total");
                pager.pagecount = parameters.Get<int>("PageCount");
                pager.pageindex = criteria.PageIndex > pager.total ? pager.total : criteria.PageIndex;
            }
            return pager;
        }

        /// <summary>
        /// 打开数据库连接字符串
        /// </summary>
        /// <returns></returns>
        public IDbConnection GetConnection()
        {
            return _db = new MySqlConnection(ConfigHelper.ConnectionString);
        }
    }
}